<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.sourceCode"
          clearable
          size="small"
          placeholder="输入数据源编码搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.sourceName"
          clearable
          size="small"
          placeholder="输入数据源名称搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <crudOperation show="" :permission="permission">
        <template v-slot:beforeExport>
          <el-button
            class="filter-item"
            :loading="downloadLoading"
            :disabled="!crud.selections.length"
            type="primary"
            size="mini"
            @click="exportData"
          ><i class="el-icon-download" />
            导出
          </el-button>
          <el-upload
            ref="uploadExcel"
            style="display: inline-block"
            class="upload-demo"
            :loading="uploadLoading"
            action=""
            multiple
            :auto-upload="false"
            :on-change="handleUploadJobChange"
            :file-list="fileList"
            :show-file-list="false"
          >
            <div>
              <el-button
                size="mini"
                class="filter-item"
                type="primary"
                icon="el-icon-upload2"
              >
                导入
              </el-button>
            </div>
          </el-upload>
          <el-button
            class="filter-item"
            :disabled="crud.selections.length !== 1"
            type="info"
            size="mini"
            @click="copyConfigInfo"
          ><i class="el-icon-document-copy" />
            复制
          </el-button>
        </template>
      </crudOperation>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
      @filter-change="crud.handleFilterChange"
      @row-dblclick="rowDbclick"
    >
      <el-table-column type="selection" />
      <el-table-column v-if="columns.visible('sourceCode')" prop="sourceCode" label="数据源编码" min-width="150" />
      <el-table-column v-if="columns.visible('sourceName')" prop="sourceName" label="数据源名称" min-width="150" />
      <el-table-column
        v-if="columns.visible('sourceType')"
        prop="sourceType"
        label="数据源类型"
        :filters="sourceTypeFilters"
        filter-placement="bottom-end"
        :filter-multiple="false"
        column-key="sourceType"
        min-width="150"
      >
        <template slot-scope="scope">
          {{ scope.row.sourceType }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('sourceAttribute')"
        key="sourceAttribute"
        label="数据源属性"
        prop="sourceAttribute"
        :filters="dataSourceAttribute"
        :filter-method="filterSourceAttribute"
        filter-placement="bottom-end"
        :filter-multiple="false"
        column-key="sourceAttribute"
      >
        <template slot-scope="scope">
          {{ findSourceAttribute(scope.row.sourceAttribute) }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('status')"
        key="status"
        label="状态"
        prop="status"
        :filters="dataStatusFilters"
        :filter-method="filterStatus"
        filter-placement="bottom-end"
        :filter-multiple="false"
        column-key="status"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            active-value="ENABLE"
            inactive-value="DISABLE"
            @change="changeEnabled(scope.row, scope.row.status)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('isDefault')"
        key="isDefault"
        label="是否默认"
        prop="isDefault"
        :filters="dataIsDefaultFilters"
        :filter-method="filterIsDefault"
        filter-placement="bottom-end"
        :filter-multiple="false"
        column-key="isDefault"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isDefault"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            active-value="ENABLE"
            inactive-value="DISABLE"
            @change="changeIsDefault(scope.row, scope.row.isDefault)"
          />
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('upUserName')" prop="upUserName" label="更新人" />
      <el-table-column v-if="columns.visible('upTs')" sortable prop="upTs" label="更新时间" min-width="150" />
    </el-table>
    <!--分页组件-->
    <pagination />

    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      top="5vh"
      width="1000px"
    >
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="160px">
        <el-form-item label="数据源编码" prop="sourceCode">
          <el-input
            v-model="form.sourceCode"
            :disabled="form.pkId != null"
            style="width: 265px;"
            :clearable="true"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="数据源名称" prop="sourceName">
          <el-input v-model="form.sourceName" :clearable="true" maxlength="30" style="width: 265px;" show-word-limit />
        </el-form-item>
        <el-form-item label="数据源类型" prop="sourceType">
          <el-select
            v-model="form.sourceType"
            :disabled="form.pkId != null"
            filterable
            style="width: 265px"
            placeholder="请选择"
            @change="initSourceConfList"
          >
            <el-option v-for="item in dict.source_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据源属性" prop="sourceAttribute">
          <el-select
            v-model="form.sourceAttribute"
            filterable
            style="width: 265px"
            placeholder="请选择"
          >
            <el-option v-for="item in dict.source_attribute" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <div v-for="(item, index) in crud.form.confInfoList" :key="index">
          <div v-if="checkShow(item)" class="dataInput">
            <el-form-item
              :label="item.confLabel"
              :prop="'confInfoList.' + index + '.confName'"
              :rules="formatterRules(item)"
            >
              <el-input
                v-if="item.valueType=='INPUT'"
                v-model="item.confName"
                :disabled="item.isShow === 'N'"
                style="width: 265px;"
              />
              <el-select
                v-if="item.valueType=='SELECT'"
                v-model="item.confName"
                :disabled="item.isShow === 'N'"
                placeholder="请选择"
                style="width: 265px;"
                @change="selectConfChange(item)"
              >
                <el-option
                  v-for="item1 in item.selectValues"
                  :key="item1.value"
                  :label="item1.text"
                  :value="item1.value"
                />
              </el-select>
              <el-input
                v-if="item.valueType=='PASS_INPUT'"
                v-model="item.confName"
                auto-complete="new-password"
                class="no-autofill-pwd"
                style="width: 265px;"
                type="text"
                :disabled="item.isShow === 'N'"
              />
            </el-form-item>
          </div>
        </div>
        <el-form-item label="描述" prop="sourceDes">
          <el-input
            v-model="form.sourceDes"
            type="textarea"
            rows="3"
            style="width: 750px"
            show-word-limit
            maxlength="50"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="crud.cancelCU">关 闭</el-button>
        <el-button :loading="crud.status.cu === 2" type="success" @click="crud.submitCU">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import dataSourceApi from '@/api/metadata/dataSource'
import sourceConfTemplateApi from '@/api/metadata/sourceConfTemplate'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/expand/metadata/CRUD.operation'
import pagination from '@crud/Pagination'
import { validateIP, validatePort, isCode } from '@utils/validate'
import { upload } from '@/api/data'
import { downloadFile } from '@/utils'
import request from '@utils/request'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '数据源', url: 'api/sourceInfo', crudMethod: { ...dataSourceApi }})
const defaultForm = {
  pkId: null,
  sourceCode: null,
  sourceName: null,
  sourceVersion: null,
  sourceTag: null,
  sourceDes: null,
  sourceType: 'MYSQL',
  sourceAttribute: 'source',
  sourceEncoding: 'UTF-8',
  confInfoList: [],
  confTemplateList: [],
  status: 'ENABLE',
  isDefault: 'DISABLE'
}
export default {
  name: 'Project',
  components: { crudOperation, rrOperation, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['data_status', 'source_type', 'source_encode', 'source_attribute'],
  data() {
    var validateSourceCode = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入数据源编码'))
      } else if (!isCode(value)) {
        callback(new Error('只能输入字母数字下划线，且以字母开头'))
      } else {
        const param = { 'sourceCode': value }
        dataSourceApi.findListByCheck(param).then(data => {
          if (data && data.pkId !== this.crud.form.pkId) {
            callback(new Error('数据源编码已经存在！'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      fileList: [],
      acceptFileType: '.xls,.xlsx',
      dialogVisible: false,
      downloadLoading: false,
      uploadLoading: false,
      permission: {
        add: ['sourceConn:add'],
        edit: ['sourceConn:edit'],
        del: ['sourceConn:del']
      },
      rules: {
        sourceEncoding: [{
          required: true,
          message: '请选择数据编码',
          trigger: 'blur'
        }],
        sourceName: [{
          required: true,
          message: '请输入数据源名称',
          trigger: 'blur'
        }],
        sourceCode: [{
          required: true,
          validator: validateSourceCode,
          trigger: 'blur'
        }],
        sourceType: [{
          required: true,
          message: '请选择数据源类型',
          trigger: 'change'
        }]
      },
      sourceTypeDict: [],
      sourceTypeFilters: [],
      sourceAttributeDict: [],
      dataSourceAttribute: [],
      dataStatusDict: [],
      dataStatusFilters: [],
      dataIsDefaultFilters: [],
      sourceConfTemplateList: [],
      copyInfo: null
    }
  },
  watch: {
    sourceAttributeDict() {
      this.$nextTick(() => {
        this.sourceAttributeDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.dataSourceAttribute.push(obj)
        })
      })
    },
    dataStatusDict() {
      this.$nextTick(() => {
        this.dataStatusDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.dataStatusFilters.push(obj)
          this.dataIsDefaultFilters.push(obj)
        })
      })
    },
    sourceTypeDict() {
      this.$nextTick(() => {
        this.sourceTypeDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.sourceTypeFilters.push(obj)
        })
      })
    }
  },
  created() {
    this.crud.resetQuery(false)
    this.sourceTypeDict = this.dict.source_type
    this.dataStatusDict = this.dict.data_status
    this.sourceAttributeDict = this.dict.source_attribute
  },
  methods: {
    async [CRUD.HOOK.beforeToAdd](crud) {
      crud.resetForm()
      if (this.copyInfo) {
        this.form.pkId = this.copyInfo.pkId
        this.form.sourceType = this.copyInfo.sourceType
        this.form.sourceAttribute = this.copyInfo.sourceAttribute
        await this.initSourceConfList()
        await this.getEditData(crud)
        this.copyInfo = null
        this.form.pkId = null
      } else {
        this.initSourceConfList()
      }
    },
    [CRUD.HOOK.beforeSubmit](crud) {
      crud.form.confInfoList.forEach(item => {
        const confName = item.oldConfName
        const confValue = item.confName
        item.confName = confName
        item.confValue = confValue
      })
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.getEditData(crud)
    },
    handleUploadJobChange(file, fileList) {
      const fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (fileName !== 'xlsx' && fileName !== 'xls') {
        this.crud.notify('文件类型应为excel文件!', CRUD.NOTIFICATION_TYPE.ERROR)
        this.fileList = []
        return false
      }
      this.fileList = fileList
      if (this.fileList.length > 0) {
        this.uploadLoading = true
        const formData = new FormData()
        this.fileList.forEach((element, i) => {
          formData.append('file', element.raw)
        })
        upload('api/sourceInfo/importMetadata', formData).then(res => {
          this.$refs.uploadExcel.clearFiles()
          this.uploadLoading = false
          if (res.status) {
            this.crud.notify('导入成功!', CRUD.NOTIFICATION_TYPE.SUCCESS)
            this.crud.refresh()
          } else {
            this.crud.notify(res.message, CRUD.NOTIFICATION_TYPE.ERROR)
          }
        })
      } else {
        this.$notify.error({
          title: '错误',
          message: '请选择导入的文件!'
        })
      }
    },
    exportData() {
      const pkIds = this.crud.selections.map(item => {
        return item.pkId
      })
      this.downloadLoading = true
      request({
        url: `api/sourceInfo/exportMetadata?pkIds=${pkIds}`,
        method: 'get',
        responseType: 'blob'
      }).then(result => {
        downloadFile(result, '数据源配置信息', 'xlsx')
        this.downloadLoading = false
      }).catch(() => {
        this.downloadLoading = false
      })
    },
    findSourceAttribute(attribute) {
      const item = this.dict.source_attribute.find(item => item.value === attribute)
      return item ? item.label : 'Not found'
    },
    rowDbclick() {
      this.dialog = true
    },
    formatterStatus(val) {
      return this.dict.label.data_status[val]
    },
    filterSourceAttribute(value, row) {
      return row.sourceAttribute === value
    },
    filterStatus(value, row) {
      return row.status === value
    },
    filterIsDefault(value, row) {
      return row.isDefault === value
    },
    arrayConversion(val, compare = (a, b) => a === b) {
      return Object.keys(this.dict.label.data_type).find(k => compare(this.dict.label.data_type[k], val))
    },
    formatterRules(item) {
      const valueRules = []
      if (item.verifyRules === 'REQUIRED') {
        let rule = { required: true, message: item.confLabel + '不能为空', trigger: 'blur' }
        if (item.valueType === 'SELECT' || item.valueType === 'RADIO') {
          rule = { required: true, message: '请选择' + item.confLabel, trigger: 'change' }
        }
        valueRules.push(rule)
      } else if (item.verifyRules === 'HOST_CHECK') {
        const rule = { required: true, validator: validateIP, trigger: 'blur' }
        valueRules.push(rule)
      } else if (item.verifyRules === 'PORT_CHECK') {
        const rule = { required: true, validator: validatePort, trigger: 'blur' }
        valueRules.push(rule)
      }
      return valueRules
    },
    getEditData(crud) {
      dataSourceApi.getSourceInfo(crud.form.pkId).then(res => {
        const confInfoList = []
        res.confTemplateList.forEach(item => {
          const confInfo = {
            confLabel: item.confLabel, valueType: item.valueType,
            selectValues: JSON.parse(item.selectValues), confDes: item.confDes,
            verifyRules: item.verifyRules, oldConfName: item.confName,
            confValue: item.confValue, confName: item.confValue,
            isShow: item.isShow, isRelevance: item.isRelevance,
            isPlaceholderAttribute: item.isPlaceholderAttribute,
            placeholderConfName: item.placeholderConfName,
            relevanceConfValue: item.relevanceConfValue,
            relevanceConfName: item.relevanceConfName
          }
          confInfoList.push(confInfo)
        })
        crud.form.confInfoList = confInfoList
      })
    },
    initSourceConfList() {
      this.crud.form.confInfoList = []
      const param = { confType: this.crud.form.sourceType, status: 'ENABLE', size: 500 }
      sourceConfTemplateApi.findListByPage(param).then(data => {
        this.sourceConfTemplateList = data.content
        data.content.forEach(item => {
          const confInfo = {
            confLabel: item.confLabel, valueType: item.valueType,
            selectValues: JSON.parse(item.selectValues), confDes: item.confDes,
            verifyRules: item.verifyRules, oldConfName: item.confName,
            confValue: item.confValue, confName: item.confValue,
            isShow: item.isShow, isRelevance: item.isRelevance,
            isPlaceholderAttribute: item.isPlaceholderAttribute,
            placeholderConfName: item.placeholderConfName,
            relevanceConfValue: item.relevanceConfValue,
            relevanceConfName: item.relevanceConfName
          }
          this.crud.form.confInfoList.push(confInfo)
        })
      })
    },
    checkShow(data) {
      if (data.isRelevance === 'N' || data.isRelevance === null) {
        return true
      }
      let relevanceValue = null
      this.form.confInfoList.forEach(item => {
        if (data.relevanceConfName === item.oldConfName) {
          relevanceValue = item.confName
        }
      })
      const relevanceConfs = JSON.parse(data.relevanceConfValue)
      if (relevanceConfs.findIndex(item => item === relevanceValue) === 0) {
        return true
      }
      return false
    },
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.data_status[val] + '" ' + data.sourceName + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        dataSourceApi.edit(data).then(res => {
          this.crud.notify(this.dict.label.data_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.status = (data.status === 'ENABLE') ? 'DISABLE' : 'ENABLE'
        })
      }).catch(() => {
        data.status = (data.status === 'ENABLE') ? 'DISABLE' : 'ENABLE'
      })
    },
    changeIsDefault(data, val) {
      this.$confirm('此操作将修改默认数据源, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        dataSourceApi.updateIsDefault(data).then(res => {
          this.crud.notify('修改默认数据源成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.refresh()
        }).catch(() => {
          data.isDefault = (data.isDefault === 'ENABLE') ? 'DISABLE' : 'ENABLE'
        })
      }).catch(() => {
        data.isDefault = (data.isDefault === 'ENABLE') ? 'DISABLE' : 'ENABLE'
      })
    },
    selectConfChange(item) {
      this.form.confInfoList = JSON.parse(JSON.stringify(this.form.confInfoList))
    },
    copyConfigInfo() {
      this.copyInfo = JSON.parse(JSON.stringify(this.crud.selections[0]))
      this.copyInfo.sourceCode = ''
      this.copyInfo.sourceName = ''
      this.crud.toAdd()
    }
  }
}
</script>

<style lang="less" scoped>
.no-autofill-pwd{
  -webkit-text-security: disc;
}
.dataInput{
  display: flex;
  float: left;
}
.el-form-item{
  margin-left: 10px;
  margin-top: 15px;
}
.dataInput:nth-of-type(6){
  margin-left: 100px;
}
</style>
